package zhuzx.solution.ir;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

import org.zhuzx.util.FileOperationUtil;
import org.zhuzx.util.GeneralUtil;
import org.zhuzx.util.MicroUtil;

/**
 * 姓名简单计算md5，取N位字母。
 * 手机号，用set存储，计数，递增序号，手机号中间用0替换，尾数为序号。
 * @author zhuzexiang
 */
public class IrExporter {
	
	private static Map<String,Integer> textSequenceMapping = new HashMap<>(20000);
	
	public static void main(String[] args) {
		Consumer<Map<String,String>> consumer =
				(Map<String,String> rec) -> mask(rec, "NAME", "PHONE_NUMBER");
		System.out.println(consumer);
//		String sql = "select * from OA.IR_ADDRESS_BOOK where create_user = 'zhuzexiang'";
//		ExportHelper.exportToSqlFile(sql, "id", consumer);

//		export("OA.IR_CLOCK_IN_INFO", "id", consumer);
//		export("OA.IR_ADDRESS_BOOK", "id", consumer);
		export("OA.IR_CONTACT_SURVEY_SUB", "id", null);
		export("OA.IR_ORG_MAPPING", "id", null);
	}
	
	private static void export(String sqlOrTableName, String uniqKey,
			Consumer<Map<String,String>> additionalProcessor) {
//		String command = "@'" + DataReplicator.exportToSqlFile(
//				sqlOrTableName, uniqKey, additionalProcessor, null) + "'";
//		GuiUtil.printOnExit(command);
	}

	private static void mask(Map<String,String> rec, String keys, String uniqKeys) {
		if (GeneralUtil.isEmpty(rec)) {
			return;
		}
		for (String key : keys.split(",")) {
			String value = generateFakeText(rec.get(key));
			rec.put(key, value);
		}
		for (String key : uniqKeys.split(",")) {
			String value = generateFakeUniqueText(rec.get(key));
			rec.put(key, value);
		}
	}
	
	private static String generateFakeText(String text) {
		if (GeneralUtil.isBlank(text)) {
			return text;
		}
		String md5 = FileOperationUtil.getMd5(text.getBytes(StandardCharsets.UTF_8));
		String capitals = GeneralUtil.concatStringExcludeBlank("", MicroUtil.extractMatches(md5, "[A-F]"));
		if (capitals == null || capitals.length() < 4) {
			text = md5.substring(0, 4);
		} else {
			text = capitals.substring(0, 4);
		}
		return text;
	}
	
	private static String generateFakeUniqueText(String text) {
		if (GeneralUtil.isBlank(text)) {
			return text;
		}
		Integer seq = textSequenceMapping.get(text);
		if (seq == null) {
			seq = textSequenceMapping.size() + 1;
			textSequenceMapping.put(text, seq);
		}
		int length = text.length();
		String thirdPart = seq.toString();
		int thirdLength = thirdPart.length();
		if (length > thirdLength + 3) {//取原手机号的前面3位加序号，中间补0。
			String firstPart = text.substring(0, 3);
			String secondPart = (MicroUtil.createRepeatedCharSequence('0', length - 3 - thirdLength));
			text = firstPart + secondPart + thirdPart;
		} else if (length > thirdLength){//长度不够，后面几位替换成序号，前面剩余长度的字符不变。
			text = text.substring(0, length - thirdLength);
		} else {//还没有序号长，只能以序号本身顶替。
			text = thirdPart;
		}
		return text;
	}
	
}